#### Figure S2: Affective Polarization Descriptives by PID Strength ####

# Libraries
# library(here)
# library(rio)
# library(tidyverse)
# library(ggthemes)
# library(srvyr)
# library(lubridate)

# data_pnas = import(here("Data","data_pnas.rds"))
# source(here("Code","Functions","funcs_theme.R"))

cs_affpol_strength = data_pnas |> 
  filter(pid7 %in% c(1:3,5:7)) |>
  mutate(pid_str = case_when(
    pid7 == 1 ~ "Strong Democrat",
    pid7 %in% 2:3 ~ "Weak/Lean Democrat",
    pid7 %in% 5:6 ~ "Weak/Lean Republican",
    pid7 == 7 ~ "Strong Republican"
  )) |>
  select(pid_str, affpol, outparty, uid, weight) |> 
  pivot_longer(affpol:outparty, names_to = "var", values_to = "val") |> 
  as_survey_design(ids = uid, weights = weight) |> # pivot_longer unsupported for svy-objects
  group_by(pid_str, var) |> 
  summarise(mean_val = survey_mean(val, na.rm = T, vartype = "ci")) |> 
  ungroup() |> 
  mutate(var = recode(var,
                      outparty = "Out-Party\nAffect",
                      affpol = "Affective\nPolarization")) |> 
  separate(pid_str, into = c("strength", "party"), sep = " ")

fig_s2 = cs_affpol_strength |> 
  ggplot(aes(x = mean_val,
             y = var,
             group = interaction(party, strength),
             label = round(mean_val, 1))) +
  geom_pointrange(aes(xmin = mean_val_low,
                      xmax = mean_val_upp,
                      color = party,
                      shape = strength),
                  position = position_dodge(.4)) +
  geom_text(aes(x = mean_val + 6),
            position = position_dodge(.4)) +
  scale_color_manual(name = "Party",
                     values = c("blue","red")) +
  scale_shape_manual(name = "PID Strength",
                     values = 16:17) +
  lims(x = c(0,100)) +
  labs(x = "Average Values",
       y = NULL,
       caption = "95% Confidence Intervals") +
  theme_prl()

print(fig_s2)

ggsave(here("Plots","Supplementary","figure_s2.png"),
       fig_s2,
       units = "in",
       width = 6, height = 4.5,
       dpi = 600)